// 主题管理
const ThemeManager = {
    init() {
        const themeToggle = document.getElementById('themeToggle');
        themeToggle.addEventListener('click', () => {
            document.body.classList.toggle('dark-theme');
            const icon = themeToggle.querySelector('i');
            icon.classList.toggle('fa-sun');
            icon.classList.toggle('fa-moon');
        });
    }
};

// 面板管理
const PanelManager = {
    init() {
        const navItems = document.querySelectorAll('.nav-item');
        const panels = document.querySelectorAll('.panel');

        navItems.forEach(item => {
            item.addEventListener('click', () => {
                const targetPanel = item.dataset.panel;
                
                // 更新导航项状态
                navItems.forEach(nav => nav.classList.remove('active'));
                item.classList.add('active');

                // 更新面板显示
                panels.forEach(panel => {
                    panel.classList.remove('active');
                    if (panel.id === `${targetPanel}Panel`) {
                        panel.classList.add('active');
                    }
                });
            });
        });
    }
};

// 番茄钟管理
const PomodoroManager = {
    workTime: 25 * 60,
    breakTime: 5 * 60,
    currentTime: 25 * 60,
    isRunning: false,
    isWorkTime: true,
    timer: null,
    completedPomodoros: 0,
    totalFocusTime: 0,

    init() {
        this.timerDisplay = document.getElementById('timerDisplay');
        this.miniTimerDisplay = document.getElementById('miniTimerDisplay');
        this.timerLabel = document.getElementById('timerLabel');
        this.startButton = document.getElementById('startTimer');
        this.pauseButton = document.getElementById('pauseTimer');
        this.resetButton = document.getElementById('resetTimer');
        this.miniPlayPause = document.getElementById('miniPlayPause');
        
        this.bindEvents();
        this.updateDisplay();
    },

    bindEvents() {
        this.startButton.addEventListener('click', () => this.start());
        this.pauseButton.addEventListener('click', () => this.pause());
        this.resetButton.addEventListener('click', () => this.reset());
        this.miniPlayPause.addEventListener('click', () => {
            if (this.isRunning) this.pause();
            else this.start();
        });
    },

    start() {
        if (!this.isRunning) {
            this.isRunning = true;
            this.startButton.disabled = true;
            this.pauseButton.disabled = false;
            this.updateMiniPlayerState(true);
            
            this.timer = setInterval(() => {
                this.currentTime--;
                this.updateDisplay();

                if (this.currentTime <= 0) {
                    this.completeInterval();
                }
            }, 1000);
        }
    },

    pause() {
        if (this.isRunning) {
            this.isRunning = false;
            clearInterval(this.timer);
            this.startButton.disabled = false;
            this.pauseButton.disabled = true;
            this.updateMiniPlayerState(false);
        }
    },

    reset() {
        this.pause();
        this.currentTime = this.workTime;
        this.isWorkTime = true;
        this.updateDisplay();
    },

    completeInterval() {
        this.pause();
        if (this.isWorkTime) {
            this.completedPomodoros++;
            this.totalFocusTime += this.workTime / 60;
            this.currentTime = this.breakTime;
            this.isWorkTime = false;
            this.showNotification('工作时间结束', '该休息一下了！');
        } else {
            this.currentTime = this.workTime;
            this.isWorkTime = true;
            this.showNotification('休息时间结束', '让我们开始新的工作吧！');
        }
        this.updateDisplay();
        this.updateStats();
    },

    updateDisplay() {
        const minutes = Math.floor(this.currentTime / 60);
        const seconds = this.currentTime % 60;
        const timeString = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
        
        this.timerDisplay.textContent = timeString;
        this.miniTimerDisplay.textContent = timeString;
        this.timerLabel.textContent = this.isWorkTime ? '工作时间' : '休息时间';
    },

    updateMiniPlayerState(isPlaying) {
        const icon = this.miniPlayPause.querySelector('i');
        icon.classList.remove(isPlaying ? 'fa-play' : 'fa-pause');
        icon.classList.add(isPlaying ? 'fa-pause' : 'fa-play');
    },

    updateStats() {
        document.getElementById('completedPomodoros').textContent = this.completedPomodoros;
        document.getElementById('totalFocusTime').textContent = `${this.totalFocusTime}分钟`;
    },

    showNotification(title, body) {
        if (Notification.permission === 'granted') {
            new Notification(title, { body });
        } else if (Notification.permission !== 'denied') {
            Notification.requestPermission().then(permission => {
                if (permission === 'granted') {
                    new Notification(title, { body });
                }
            });
        }
    }
};

// 任务管理
const TaskManager = {
    tasks: [],

    init() {
        this.bindEvents();
        this.loadTasks();
        this.renderTasks();
    },

    bindEvents() {
        const addTaskBtn = document.getElementById('addTaskBtn');
        const taskModal = document.getElementById('taskModal');
        const closeButtons = document.querySelectorAll('.close-modal');
        const saveTaskBtn = document.getElementById('saveTask');

        addTaskBtn.addEventListener('click', () => {
            taskModal.classList.add('active');
        });

        closeButtons.forEach(button => {
            button.addEventListener('click', () => {
                taskModal.classList.remove('active');
            });
        });

        saveTaskBtn.addEventListener('click', () => this.saveTask());

        // 任务过滤器
        const filterButtons = document.querySelectorAll('.filter-btn');
        filterButtons.forEach(button => {
            button.addEventListener('click', () => {
                filterButtons.forEach(btn => btn.classList.remove('active'));
                button.classList.add('active');
                this.filterTasks(button.dataset.filter);
            });
        });
    },

    saveTask() {
        const title = document.getElementById('taskTitle').value;
        const pomodoros = parseInt(document.getElementById('taskPomodoros').value);
        const priority = document.getElementById('taskPriority').value;
        const date = document.getElementById('taskDate').value;

        if (title) {
            const task = {
                id: Date.now(),
                title,
                pomodoros,
                priority,
                date,
                completed: false,
                createdAt: new Date().toISOString()
            };

            this.tasks.push(task);
            this.saveTasks();
            this.renderTasks();
            document.getElementById('taskModal').classList.remove('active');
            document.getElementById('taskForm').reset();
        }
    },

    toggleTask(id) {
        const task = this.tasks.find(t => t.id === id);
        if (task) {
            task.completed = !task.completed;
            this.saveTasks();
            this.renderTasks();
        }
    },

    deleteTask(id) {
        this.tasks = this.tasks.filter(t => t.id !== id);
        this.saveTasks();
        this.renderTasks();
    },

    filterTasks(filter) {
        const tasksList = document.getElementById('tasksList');
        tasksList.innerHTML = '';

        const today = new Date().toISOString().split('T')[0];
        const filteredTasks = this.tasks.filter(task => {
            switch (filter) {
                case 'today':
                    return task.date === today;
                case 'week':
                    const taskDate = new Date(task.date);
                    const weekFromNow = new Date();
                    weekFromNow.setDate(weekFromNow.getDate() + 7);
                    return taskDate <= weekFromNow;
                default:
                    return true;
            }
        });

        this.renderTasksList(filteredTasks);
    },

    renderTasks() {
        const activeFilter = document.querySelector('.filter-btn.active').dataset.filter;
        this.filterTasks(activeFilter);
    },

    renderTasksList(tasks) {
        const tasksList = document.getElementById('tasksList');
        tasksList.innerHTML = '';

        tasks.forEach(task => {
            const taskElement = document.createElement('div');
            taskElement.className = `task-item priority-${task.priority}`;
            taskElement.innerHTML = `
                <input type="checkbox" ${task.completed ? 'checked' : ''}>
                <div class="task-content">
                    <span class="task-title">${task.title}</span>
                    <span class="task-meta">
                        <i class="fas fa-clock"></i> ${task.pomodoros} 个番茄钟
                        <i class="fas fa-calendar"></i> ${task.date}
                    </span>
                </div>
                <button class="delete-task" onclick="TaskManager.deleteTask(${task.id})">
                    <i class="fas fa-trash"></i>
                </button>
            `;

            const checkbox = taskElement.querySelector('input');
            checkbox.addEventListener('change', () => this.toggleTask(task.id));

            tasksList.appendChild(taskElement);
        });
    },

    loadTasks() {
        const savedTasks = localStorage.getItem('tasks');
        if (savedTasks) {
            this.tasks = JSON.parse(savedTasks);
        }
    },

    saveTasks() {
        localStorage.setItem('tasks', JSON.stringify(this.tasks));
    }
};

// 白噪音管理
const SoundManager = {
    sounds: {},
    activeSounds: 0,

    init() {
        this.initializeSounds();
        this.bindEvents();
    },

    initializeSounds() {
        const soundCards = document.querySelectorAll('.sound-card');
        
        soundCards.forEach(card => {
            const soundId = card.dataset.sound;
            const audio = new Audio(`sounds/${soundId}.mp3`);
            audio.loop = true;

            this.sounds[soundId] = {
                audio,
                isPlaying: false,
                volume: 0.5
            };

            // 音量控制
            const slider = card.querySelector('.volume-slider');
            slider.addEventListener('input', (e) => {
                this.updateVolume(soundId, e.target.value / 100);
            });

            // 点击播放/暂停
            card.addEventListener('click', (e) => {
                if (!e.target.classList.contains('volume-slider')) {
                    this.toggleSound(soundId);
                }
            });
        });
    },

    bindEvents() {
        // 主音量控制
        const masterVolume = document.querySelector('.master-volume');
        masterVolume.addEventListener('click', () => {
            const icon = masterVolume.querySelector('i');
            const isMuted = icon.classList.contains('fa-volume-mute');
            
            Object.keys(this.sounds).forEach(soundId => {
                const sound = this.sounds[soundId];
                if (sound.isPlaying) {
                    sound.audio.volume = isMuted ? sound.volume : 0;
                }
            });

            icon.classList.toggle('fa-volume-up');
            icon.classList.toggle('fa-volume-mute');
        });
    },

    toggleSound(soundId) {
        const sound = this.sounds[soundId];
        const soundCard = document.querySelector(`[data-sound="${soundId}"]`);
        
        if (sound.isPlaying) {
            sound.audio.pause();
            sound.isPlaying = false;
            this.activeSounds--;
            soundCard.classList.remove('playing');
        } else {
            sound.audio.play();
            sound.isPlaying = true;
            this.activeSounds++;
            soundCard.classList.add('playing');
        }

        this.updateActiveSoundsCount();
    },

    updateVolume(soundId, value) {
        const sound = this.sounds[soundId];
        sound.volume = value;
        sound.audio.volume = value;
    },

    updateActiveSoundsCount() {
        document.getElementById('activeSoundsCount').textContent = this.activeSounds;
    }
};

// 初始化应用
document.addEventListener('DOMContentLoaded', () => {
    ThemeManager.init();
    PanelManager.init();
    PomodoroManager.init();
    TaskManager.init();
    SoundManager.init();
});
